package com.xxgc.qinglian.qinglianserver.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xxgc.qinglian.qinglianserver.entity.ProjectEntity;
import com.xxgc.qinglian.qinglianserver.entity.ProjectEntityRepository;
import com.xxgc.qinglian.qinglianserver.websocket.VoteWebSocketHandler;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WebSocketService {

    private final VoteWebSocketHandler webSocketHandler;
    private final ProjectEntityRepository projectRepository;

    public WebSocketService(VoteWebSocketHandler webSocketHandler,
                            ProjectEntityRepository projectRepository) {
        this.webSocketHandler = webSocketHandler;
        this.projectRepository = projectRepository;
    }

    // 点对点发送剩余票数给用户
    public void sendRemainingVotesToUser(Integer userId, int remainingVotes) {
        Map<String, Object> data = new HashMap<>();
        data.put("type", "remainingVotes");
        data.put("remainingVotes", remainingVotes);
        webSocketHandler.sendMessageToUser(userId, data);
    }

    // 广播项目票数更新给所有用户
    public void broadcastProjectVotesUpdate() {
        List<ProjectEntity> projects = projectRepository.list();
        Map<String, Object> data = new HashMap<>();
        data.put("type", "projectVotes");
        data.put("projects", projects);
        webSocketHandler.broadcastMessage(data);
    }
}